// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    loadElderlyOptions();
});

// 加载老年人选项
async function loadElderlyOptions() {
    try {
        const response = await fetch('/api/elderly');
        const data = await response.json();
        const select = document.getElementById('elderlySelect');
        
        data.forEach(elderly => {
            const option = document.createElement('option');
            option.value = elderly.id;
            option.textContent = elderly.name;
            select.appendChild(option);
        });
    } catch (error) {
        console.error('Error:', error);
    }
}

// 加载健康记录
async function loadHealthRecords(elderlyId) {
    if (!elderlyId) {
        document.getElementById('record-list').innerHTML = '';
        return;
    }

    try {
        const response = await fetch(`/api/health_record?elderly_id=${elderlyId}`);
        const data = await response.json();
        const tbody = document.getElementById('record-list');
        
        let html = '';
        data.forEach(record => {
            const indicators = record.indicators || {};
            const statusClass = getHealthStatusClass(record.health_status);
            html += `
                <tr>
                    <td>${record.record_date}</td>
                    <td>${indicators.temperature || '-'}</td>
                    <td>${indicators.blood_pressure ? 
                         indicators.blood_pressure.systolic + '/' + 
                         indicators.blood_pressure.diastolic : '-'}</td>
                    <td class="health-status ${statusClass}">${record.health_status || '-'}</td>
                    <td>${record.description || '-'}</td>
                    <td>${record.doctor_advice || '-'}</td>
                </tr>
            `;
        });
        
        tbody.innerHTML = html;
    } catch (error) {
        console.error('Error:', error);
    }
}

// 显示添加记录表单
function showAddRecordForm() {
    const elderlyId = document.getElementById('elderlySelect').value;
    if (!elderlyId) {
        alert('请先选择老年人！');
        return;
    }

    document.body.insertAdjacentHTML('beforeend', '<div class="modal-overlay"></div>');
    
    const form = `
        <div class="modal">
            <h3>添加健康记录</h3>
            <form id="record-form">
                <input type="hidden" name="elderly_id" value="${elderlyId}">
                <div>
                    <label>体温(℃)：</label>
                    <input type="number" name="temperature" step="0.1" required>
                </div>
                <div>
                    <label>收缩压(mmHg)：</label>
                    <input type="number" name="systolic_pressure" required>
                </div>
                <div>
                    <label>舒张压(mmHg)：</label>
                    <input type="number" name="diastolic_pressure" required>
                </div>
                <div>
                    <label>记录时间：</label>
                    <input type="datetime-local" name="record_date" required>
                </div>
                <div>
                    <label>描述：</label>
                    <textarea name="description" rows="3"></textarea>
                </div>
                <div>
                    <label>医生建议：</label>
                    <textarea name="doctor_advice" rows="3"></textarea>
                </div>
                <div class="form-buttons">
                    <button type="submit">提交</button>
                    <button type="button" onclick="closeModal()">取消</button>
                </div>
            </form>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', form);
    
    // 设置当前时间为默认值
    const now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    document.querySelector('input[name="record_date"]').value = now.toISOString().slice(0, 16);
    
    document.getElementById('record-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData.entries());
        
        const recordData = {
            elderly_id: parseInt(data.elderly_id),
            record_type: '日常监测',
            record_date: data.record_date,
            description: data.description || '',
            doctor_advice: data.doctor_advice || '',
            indicators: {
                temperature: parseFloat(data.temperature),
                blood_pressure: {
                    systolic: parseInt(data.systolic_pressure),
                    diastolic: parseInt(data.diastolic_pressure)
                }
            }
        };
        
        try {
            const response = await fetch('/api/health_record', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(recordData)
            });
            
            const result = await response.json();
            
            if (result.success) {
                alert('记录添加成功！');
                closeModal();
                loadHealthRecords(data.elderly_id);
            } else {
                alert('添加失败：' + result.message);
            }
        } catch (error) {
            console.error('Error:', error);
            alert('提交出错，请重试！');
        }
    });
}

// 获取健康状态样式类
function getHealthStatusClass(status) {
    switch(status) {
        case '非常健康': return 'status-excellent';
        case '良好': return 'status-good';
        case '及格': return 'status-fair';
        case '需要治疗': return 'status-poor';
        default: return '';
    }
}

// 关闭模态框
function closeModal() {
    document.querySelector('.modal').remove();
    document.querySelector('.modal-overlay').remove();
} 